import 'dart:async';
import 'dart:ffi';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HeartRateData with ChangeNotifier {
    static HeartRateData? _instance;
     // 私有构造函数
  HeartRateData._internal();

   // 单例访问点
  static HeartRateData get instance {
    _instance ??= HeartRateData._internal();
    return _instance!;
  }
  // 防止对象被克隆
  @override
  dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
  
    void start() {
    if (_isRunning) return;
    _isRunning = true;
    // 启动数据采集逻辑
    _simulateData();
    notifyListeners();
  }

  void stop() {
    _isRunning = false;
    // 停止数据采集
    notifyListeners();
  }

  void reset() {
    if (!_isRunning) {
      _heartRate_data_list.clear();
      _heartRate_DataTime_list .clear();
      _currentHeartRate=0;
      _avgHeartRate=0.0;
      _maxHeartRate=0;
      _minHeartRate=0;
   
      notifyListeners();
    }
  }
    late Timer _timer;
   void _simulateData() {
    // 模拟数据生成逻辑
       // 模拟数据更新（每2秒更新一次）
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      final random = math.Random();
     var randoms= (random.nextInt(30) + 100);
   
      final newRate = randoms;

      updateHeartRate(newRate.clamp(40, 240));
    });
  }
//     // 数据持久化存储
//   Future<void> saveToStorage() async {
//     final prefs = await SharedPreferences.getInstance();
//     await prefs.setStringList('heart_rates', 
//       _heartRate_data_list.map((r) => r.toString()).toList());
//     await prefs.setString('last_update', hr_lastUpdate?.toIso8601String() ?? '');
//   }

//   // 从存储加载数据
//   Future<void> loadFromStorage() async {
//     final prefs = await SharedPreferences.getInstance();
//     _heartRate_data_list = prefs.getStringList('heart_rates')?.map(int.parse).toList() ?? [];
//     final lastUpdateStr = prefs.getString('last_update');
//     hr_lastUpdate = lastUpdateStr != null ? DateTime.parse(lastUpdateStr) : null;
//     notifyListeners();
//   }
// }
  /// 存储心率绘制曲线的列表
  List<HeartRatePoint> _heartRate_chart_data = [];

  /// 存储心率数据的列表
  List<int> _heartRate_data_list = [];
  
  /// 存储心率数据对应时间的列表
  List<DateTime> _heartRate_DataTime_list = [];
  
  /// 用户名
  String _userName="";
  
  /// 活动类型
  String _activityType="";
  
  /// 当前心率
  int _currentHeartRate=0;
  
  /// 平均心率
  double _avgHeartRate=0.0;
  
  /// 最大心率
  int _maxHeartRate=0;
  
  /// 最小心率
  int _minHeartRate=0;
  
  /// 心率的最大限制
  final int maxHeartRateLimit=240;
/// 心率数据更新时间
  DateTime _hr_lastUpdate=DateTime.now();

  // 新增字段
  /// 设备名称
  String _devicesName="";
  
  /// 设备MAC地址
  String _devicesMac="";
  
  /// 设备电池电量
  int _devicesBattery=0;
  
  /// 用户身高（单位：米）
  double _height=0.0;
  
  /// 用户体重（单位：千克）
  double _weight=0.0;
  
  /// 用户年龄
  int _age=0;
  
  /// 用户性别
  String _gender="";
  
  /// 是否正在运行
  bool _isRunning=false;
  
  /// 备注信息
  String _notes="";
  

  /// 额外的日期列表
  List<DateTime> _additionalDates=[];

  ///最后更新时间
  DateTime _lastUpdateTime=DateTime.now();



  // Getters
  /// 获取用户名
  String get userName => _userName;
  /// 获取活动类型
  String get activityType => _activityType;
  /// 获取当前心率
  int get currentHeartRate => _currentHeartRate;
  /// 获取平均心率
  double get avgHeartRate => _avgHeartRate;
  /// 获取最大心率
  int get maxHeartRate => _maxHeartRate;
  /// 获取最小心率
  int get minHeartRate => _minHeartRate;
  /// 心率数据更新时间
  DateTime get hr_lastUpdate => _hr_lastUpdate;

 
  // 新增 Getters
  /// 获取设备名称
  String get devicesName => _devicesName;
  /// 获取设备MAC地址
  String get devicesMac => _devicesMac;
  /// 获取设备电池电量
  int get devicesBattery => _devicesBattery;
  /// 获取用户身高
  double get height => _height;
  /// 获取用户体重
  double get weight => _weight;
  /// 获取用户年龄
  int get age => _age;
  /// 获取用户性别
  String get gender => _gender;
  /// 获取是否正在运行
  bool get isRunning => _isRunning;
  /// 获取备注信息
  String get notes => _notes;
  /// 获取额外的日期列表
  List<DateTime> get additionalDates => _additionalDates;

  /// 存储心率数据的列表
  List<int>get heartRate_data_list => _heartRate_data_list;
  
  /// 存储心率数据对应时间的列表
  List<DateTime> get heartRate_DataTime_list=> _heartRate_DataTime_list;

  ///最后更新时间
    DateTime get lastUpdateTime=> _lastUpdateTime;
/// 存储心率绘制曲线的列表
  List<HeartRatePoint> get heartRate_chart_data => _heartRate_chart_data;
  // Setters

  /// 添加心率曲线数据时更新chart数据
   void add_heartRate_chart_data(HeartRatePoint point) {
    _heartRate_chart_data.add(point);
    notifyListeners(); // 触发界面更新
  }
    /// 设置用户名
    set userName(String value) {
    _userName = value;
    notifyListeners();
  }

  
  /// 设置率数据更新时间
  set hr_lastUpdate(DateTime value) {
    _hr_lastUpdate = value;
    notifyListeners();
  }
  ///设置活动类型
  set activityType(String value) {
    _activityType = value;
    notifyListeners();
  }
/// 设置当前心率
  set currentHeartRate(int value) {
    _currentHeartRate = value;
    notifyListeners();
  }
/// 设置平均心率
  set avgHeartRate(double value) {
    _avgHeartRate = value;
    notifyListeners();
  }
/// 设置最大心率
  set maxHeartRate(int value) {
    _maxHeartRate = value;
    notifyListeners();
  }
/// 设置最小心率
  set minHeartRate(int value) {
    _minHeartRate = value;
    notifyListeners();
  }
/// 设置设备名称
  set devicesName(String value) {
    _devicesName = value;
    notifyListeners();
  }
/// 设置设备MAC地址
  set devicesMac(String value) {
    _devicesMac = value;
    notifyListeners();
  }
/// 设置设备电池电量
  set devicesBattery(int value) {
    _devicesBattery = value;
    notifyListeners();
  }
/// 设置用户身高
  set height(double value) {
    _height = value;
    notifyListeners();
  }
/// 设置用户体重
  set weight(double value) {
    _weight = value;
    notifyListeners();
  }
/// 设置用户年龄
  set age(int value) {
    _age = value;
    notifyListeners();
  }
/// 设置用户性别
  set gender(String value) {
    _gender = value;
    notifyListeners();
  }
/// 设置是否正在运行
  set isRunning(bool value) {
    _isRunning = value;
    notifyListeners();
  }
/// 设置备注信息
  set notes(String value) {
    _notes = value;
    notifyListeners();
  }
  set heartRate_data_list(var value){
    _heartRate_data_list = value;
    notifyListeners();
  }
  set heartRate_DataTime_list(List<DateTime> value){
    _heartRate_DataTime_list = value;
    notifyListeners();
  }
  set additionalDates(List<DateTime> value){
    _additionalDates = value;
    notifyListeners();
  }
  set lastUpdateTime(DateTime value){
    _lastUpdateTime = value;
    notifyListeners();
  }
  
  
  
  
  // 更新方法
  void updateHeartRate(int newRate) {
    var nowTime=DateTime.now();
    _heartRate_data_list.add(newRate);
    // 获取当前时间
    _heartRate_DataTime_list.add(nowTime);
    _currentHeartRate = newRate;
    _avgHeartRate = double.parse((_heartRate_data_list.reduce((a, b) => a + b) / _heartRate_data_list.length).toStringAsFixed(1));
    _maxHeartRate = _heartRate_data_list.reduce((a, b) => a > b ? a : b);
    _minHeartRate = _heartRate_data_list.reduce((a, b) => a < b ? a : b);

    _maxHeartRate = math.max(_maxHeartRate, newRate);
    _minHeartRate = math.min(_minHeartRate, newRate);
    //print('当前心率:' + _currentHeartRate.toString());
    add_heartRate_chart_data(HeartRatePoint(_currentHeartRate, nowTime));
    hr_lastUpdate=nowTime;
      print('${nowTime} 当前心率：  '+_currentHeartRate.toString());
    notifyListeners();
  }

    // 数据操作方法
  void addData(int rate, DateTime time) {
    heartRate_data_list.add(rate);
    heartRate_DataTime_list.add(time);
  }

  Future<void> saveToStorage() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('rates', heartRate_data_list.map((r) => r.toString()).toList());
    await prefs.setStringList('times', 
      heartRate_DataTime_list.map((t) => t.toIso8601String()).toList());
  }

  Future<void> loadFromStorage() async {
    final prefs = await SharedPreferences.getInstance();
    heartRate_data_list = prefs.getStringList('rates')?.map(int.parse).toList() ?? [];
    heartRate_DataTime_list = prefs.getStringList('times')
      ?.map((t) => DateTime.parse(t))
      .toList() ?? [];
  }
}

class HeartRatePoint {
  final int value;     // 心率值（单位：BPM，如 75.0）
  final DateTime timestamp; // 数据记录时间戳

  HeartRatePoint(this.value, this.timestamp);
}